package com.lw.thread;

/**
 * @author LW
 * @2020/8/18 15:16
 */
//死锁：多个线程互相抱着对方需要的资源，然后形成僵持
public class DeadLock {
//要毕业生，还要有工作经验。就死锁了。。

    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"小芸");
        Makeup g2 = new Makeup(1,"小清");
        g1.start();
        g2.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}

//化妆
class Makeup extends Thread{

    //需要的资源只有一份
    //因为是static的，两个线程拿的才是同一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choose;//选择
    String girlName;//化妆的人

    Makeup(int choose,String girlName){
        this.choose=choose;
        this.girlName=girlName;
    }


    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeup() throws InterruptedException {
        if (choose==0){
            synchronized (lipstick){//获得口红的锁
                System.out.println(this.girlName+"获得口红的锁");
                Thread.sleep(1000);

//                synchronized (mirror){//一秒钟后获得镜子的锁
//                    System.out.println(this.girlName+"获得镜子的锁");
//
//                }
            }
            //代码块分开   就抱两把锁了
            synchronized (mirror){//一秒钟后获得镜子的锁
                System.out.println(this.girlName+"获得镜子的锁");

            }
        }else {
            synchronized (mirror){//获得镜子的锁
                System.out.println(this.girlName+"获得镜子的锁");
                Thread.sleep(2000);
//                synchronized (lipstick){//一秒钟后获得口红的锁
//                    System.out.println(this.girlName+"获得口红的锁");
//
//                }
            }
            synchronized (lipstick){//一秒钟后获得口红的锁
                System.out.println(this.girlName+"获得口红的锁");

            }
        }
    }
}